<!DOCTYPE html>


<html lang="en">
  

    <head>
      <meta charset="utf-8" />
        
      <meta
        name="viewport"
        content="width=device-width, initial-scale=1, maximum-scale=1"
      />
      <title> 豆 扁</title>
  <meta name="generator" content="hexo-theme-ayer">
      
      <link rel="shortcut icon" href="/favicon.ico" />
       
<link rel="stylesheet" href="/dist/main.css">

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css"
      />
      
<link rel="stylesheet" href="/css/custom.css">
 
      <script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>
       
 

      <!-- mermaid -->
      
    <link rel="alternate" href="/atom.xml" title="豆 扁" type="application/atom+xml">
</head>
  </html>
</html>


<body>
  <div id="app">
    
      
    <main class="content on">
      
<section class="cover">
    
  <div class="cover-frame">
    <div class="bg-box">
      <img src="/images/cover1.jpg" alt="image frame" />
    </div>
    <div class="cover-inner text-center text-white">
      <h1><a href="/">豆 扁</a></h1>
      <div id="subtitle-box">
        
        <span id="subtitle"></span>
        
      </div>
      <div>
        
      </div>
    </div>
  </div>
  <div class="cover-learn-more">
    <a href="javascript:void(0)" class="anchor"><i class="ri-arrow-down-line"></i></a>
  </div>
</section>



<script src="https://cdn.jsdelivr.net/npm/typed.js@2.0.11/lib/typed.min.js"></script>


<!-- Subtitle -->

  <script>
    try {
      var typed = new Typed("#subtitle", {
        strings: ['面朝大海，春暖花开', '愿你一生努力，一生被爱', '想要的都拥有，得不到的都释怀'],
        startDelay: 0,
        typeSpeed: 200,
        loop: true,
        backSpeed: 100,
        showCursor: true
      });
    } catch (err) {
      console.log(err)
    }
  </script>
  
<div id="main">
  <section class="outer">
  
  
  

<div class="notice" style="margin-top:50px">
    <i class="ri-heart-fill"></i>
    <div class="notice-content" id="broad"></div>
</div>
<script type="text/javascript">
    fetch('https://v1.hitokoto.cn')
        .then(response => response.json())
        .then(data => {
            document.getElementById("broad").innerHTML = data.hitokoto;
        })
        .catch(console.error)
</script>

<style>
    .notice {
        padding: 20px;
        border: 1px dashed #e6e6e6;
        color: #969696;
        position: relative;
        display: inline-block;
        width: 100%;
        background: #fbfbfb50;
        border-radius: 10px;
    }

    .notice i {
        float: left;
        color: #999;
        font-size: 16px;
        padding-right: 10px;
        vertical-align: middle;
        margin-top: -2px;
    }

    .notice-content {
        display: initial;
        vertical-align: middle;
    }
</style>
  
  <article class="articles">
    
    
    
    
    <article
  id="post-线程池"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h2 itemprop="name">
  <a class="article-title" href="/2021/06/23/%E7%BA%BF%E7%A8%8B%E6%B1%A0/"
    >线程池</a> 
</h2>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2021/06/23/%E7%BA%BF%E7%A8%8B%E6%B1%A0/" class="article-date">
  <time datetime="2021-06-23T12:39:25.000Z" itemprop="datePublished">2021-06-23</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/">并发编程</a>
  </div>
   
    </div>
      
    <div class="article-entry" itemprop="articleBody">
       
  <h2 id="1、为什么使用线程池"><a href="#1、为什么使用线程池" class="headerlink" title="1、为什么使用线程池"></a>1、为什么使用线程池</h2><p>原因：频繁的创建线程销毁线程，会消耗系统资源，降低系统稳定性</p>
<p>优点：1、降低频繁创建销毁线程的资源消耗</p>
<p>​            2、使用已有的线程执行任务，减少创建线程步骤，减少响应时间</p>
<p>​            3、提高线程可管理性</p>
<h2 id="2、线程池核心参数"><a href="#2、线程池核心参数" class="headerlink" title="2、线程池核心参数"></a>2、线程池核心参数</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">ThreadPoolExecutor</span><span class="params">(<span class="keyword">int</span> corePoolSize,</span></span></span><br><span class="line"><span class="params"><span class="function">                              <span class="keyword">int</span> maximumPoolSize,</span></span></span><br><span class="line"><span class="params"><span class="function">                              <span class="keyword">long</span> keepAliveTime,</span></span></span><br><span class="line"><span class="params"><span class="function">                              TimeUnit unit,</span></span></span><br><span class="line"><span class="params"><span class="function">                              BlockingQueue&lt;Runnable&gt; workQueue,</span></span></span><br><span class="line"><span class="params"><span class="function">                              ThreadFactory threadFactory,</span></span></span><br><span class="line"><span class="params"><span class="function">                              RejectedExecutionHandler handler)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (corePoolSize &lt; <span class="number">0</span> ||</span><br><span class="line">            maximumPoolSize &lt;= <span class="number">0</span> ||</span><br><span class="line">            maximumPoolSize &lt; corePoolSize ||</span><br><span class="line">            keepAliveTime &lt; <span class="number">0</span>)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException();</span><br><span class="line">        <span class="keyword">if</span> (workQueue == <span class="keyword">null</span> || threadFactory == <span class="keyword">null</span> || handler == <span class="keyword">null</span>)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> NullPointerException();</span><br><span class="line">        <span class="keyword">this</span>.acc = System.getSecurityManager() == <span class="keyword">null</span> ?</span><br><span class="line">                <span class="keyword">null</span> :</span><br><span class="line">                AccessController.getContext();</span><br><span class="line">        <span class="keyword">this</span>.corePoolSize = corePoolSize;</span><br><span class="line">        <span class="keyword">this</span>.maximumPoolSize = maximumPoolSize;</span><br><span class="line">        <span class="keyword">this</span>.workQueue = workQueue;</span><br><span class="line">        <span class="keyword">this</span>.keepAliveTime = unit.toNanos(keepAliveTime);</span><br><span class="line">        <span class="keyword">this</span>.threadFactory = threadFactory;</span><br><span class="line">        <span class="keyword">this</span>.handler = handler;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><p><strong>corePoolSize</strong>：线程池核心线程数，比喻为一个公司的正式员工</p>
</li>
<li><p><strong>maximumPoolSize</strong>：线程池最大线程数，比喻为一个公司的正式员工+临时外包员工的总数</p>
</li>
<li><p><strong>keepAliveTime + unit：</strong>超过线程池核心线程数之外部分的线程多长时间没有执行任务就被销毁</p>
</li>
<li><p><strong>workQueue</strong>：线程池核心线程满之后，将后来的任务放入队列中排队等待执行。</p>
<p> 1、ArrayBlockingQueue：基于数组结构的有界阻塞队列，按FIFO排序任务；<br> 2、LinkedBlockingQuene：基于链表结构的阻塞队列，按FIFO排序任务，吞吐量通常要高于ArrayBlockingQueue;<br> 3、SynchronousQuene：一个不存储元素的阻塞队列，每个插入操作必须等到另一个线程调用移除操作，否则插入操作一直处于阻塞状态，吞吐量通常要高于LinkedBlockingQuene；<br> 4、priorityBlockingQuene：具有优先级的无界阻塞队列；</p>
</li>
<li><p><strong>threadFactory</strong>：线程工厂，可以使用ThreadFactoryBuilder创建，主要用于创建线程时给线程规范命名</p>
</li>
<li><p><strong>RejectedExecutionHandler</strong>：线程池到达最大线程数，且工作队列已满之后的拒绝策略</p>
<p>1、AbortPolicy: 丢弃任务并抛出RejectedExecutionException异常</p>
<p>2、DiscardPolicy：丢弃任务，但是不抛出异常。如果线程队列已满，则后续提交的任务都会被丢弃，且是静默丢弃</p>
<p>3、DiscardOldestPolicy：丢弃队列最前面的任务，然后重新提交被拒绝的任务</p>
<p>4、CallerRunsPolicy：由调用线程处理该任务</p>
<p>5、创建自定义拒绝策略实现RejectedExecutionHandler接口</p>
</li>
</ul>
<h2 id="3、线程池执行流程"><a href="#3、线程池执行流程" class="headerlink" title="3、线程池执行流程"></a>3、线程池执行流程</h2><p><img src="https://blog-cl.oss-cn-shenzhen.aliyuncs.com/%E7%BA%BF%E7%A8%8B%E6%B1%A0%E6%89%A7%E8%A1%8C%E6%B5%81%E7%A8%8B"></p>
<h2 id="4、submit和execute的区别"><a href="#4、submit和execute的区别" class="headerlink" title="4、submit和execute的区别"></a>4、submit和execute的区别</h2><p>1、execute方法只能传入Runnable类型的任务，execute可以传入Runnable类型和Callable类型的任务</p>
<p>1、execute方法不返回执行结果，submit方法返回Future对象（之后传入Callable类型任务才会有返回结果，否则future.get()返回null）</p>
<p>2、execute方法任务执行过程中异常会抛出，submit方法任务执行过程中的异常会被捕获然后返回到Future对象中</p>
<p>3、submit方法提交任务需要判断返回对象是否异常，或者直接给线程工厂设置异常处理例如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">ThreadFactory namedThreadFactory = <span class="keyword">new</span> ThreadFactoryBuilder()</span><br><span class="line">                .setNameFormat(<span class="string">&quot;judge-pool-%d&quot;</span>)</span><br><span class="line">                .setUncaughtExceptionHandler((thread, throwable)-&gt; logger.error(<span class="string">&quot;ThreadPool &#123;&#125; got exception&quot;</span>, thread,throwable))</span><br><span class="line">                .build();</span><br></pre></td></tr></table></figure>

<p>这样就可以在任务执行异常后答应异常日志</p>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/" rel="tag">并发编程</a></li></ul>

    </footer>
  </div>

   
    
</article>

    
    <article
  id="post-synchronize"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h2 itemprop="name">
  <a class="article-title" href="/2021/06/22/synchronize/"
    >synchronize</a> 
</h2>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2021/06/22/synchronize/" class="article-date">
  <time datetime="2021-06-22T15:59:20.000Z" itemprop="datePublished">2021-06-22</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/">并发编程</a>
  </div>
   
    </div>
      
    <div class="article-entry" itemprop="articleBody">
       
  <h2 id="1、Synchronize使用"><a href="#1、Synchronize使用" class="headerlink" title="1、Synchronize使用"></a>1、Synchronize使用</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 修饰静态方法，给方法对应的class对象加锁</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> synchronize staic <span class="keyword">void</span> <span class="title">Test</span><span class="params">()</span></span>&#123;&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 修饰普通方法，给方法对应的实例对象加锁</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> synchornize <span class="keyword">void</span> <span class="title">Test</span><span class="params">()</span></span>&#123;&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 修饰代码块，给方法对应的class对象加锁</span></span><br><span class="line">synchornize(Test.class)&#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 修饰代码块，给方法对应的实例对象加锁(注意：错误的加锁方式，每次加锁都是一个新的实例，等于没加锁)</span></span><br><span class="line">synchornize(<span class="keyword">new</span> Test())&#123;&#125;</span><br></pre></td></tr></table></figure>



<h2 id="2、Synchronize保证的特性"><a href="#2、Synchronize保证的特性" class="headerlink" title="2、Synchronize保证的特性"></a>2、Synchronize保证的特性</h2><ul>
<li>有序性：在synchronize代码块中加入屏障，代码块中的读操作和写操作之间禁止指令重排</li>
<li>可见性：线程获取到锁之后，清空工作内存中的缓存，使用到变量的时候重新去主存中获取，释放锁之前将缓存中的值强制刷新到主存中</li>
<li>原子性：一次只允许一个线程获得锁</li>
<li>可重入性：维护一个计数器，未加锁之前计数器为0，加锁一次计数器加1，同一个线程重入继续加1，释放一次锁极速器减一，直到计数器为0时，其他线程才可以抢占锁</li>
<li>不可中断性：一个线程获取锁之后，在未释放之前，其他线程一直等待，不可能中断</li>
</ul>
<h2 id="3、Synchronize执行原理"><a href="#3、Synchronize执行原理" class="headerlink" title="3、Synchronize执行原理"></a>3、Synchronize执行原理</h2><ul>
<li><p>  java对象存储结构</p>
<pre><code>  ![](https://blog-cl.oss-cn-shenzhen.aliyuncs.com/java%E5%AF%B9%E8%B1%A1%E7%BB%93%E6%9E%84.png)
</code></pre>
</li>
</ul>
<blockquote>
<p>tip: 一个空的java对象占用8个字节，因为对齐填充</p>
</blockquote>
<p>1、通过monitorenter字节码指令获取对象对应的monitor对象（每个java对象天生自带一个monitor对象）</p>
<p>2、在monitor对象中保存线程占有信息</p>
<p>3、如果再次获取锁时，发现monitor对象中的占有线程是当前线程，计数器+1</p>
<p>4、通过monitorexist字节码指令释放锁，计数器-1</p>
<h2 id="4、Synchronize锁升级"><a href="#4、Synchronize锁升级" class="headerlink" title="4、Synchronize锁升级"></a>4、Synchronize锁升级</h2><p>为什么有锁升级：jdk1.5之前Synchronize都是使用重锁，但是因为线程的阻塞和唤起操作需要来用户态和内核态之前来回切换，切换过程会消耗大量的系统资源，所以jdk1.6之后增加了Synchronize锁升级机制</p>
<p>升级过程：  无锁   =》 偏向锁  =》 轻量锁  =》  重量锁</p>
<ul>
<li><h4 id="偏向锁"><a href="#偏向锁" class="headerlink" title="偏向锁"></a>偏向锁</h4></li>
</ul>
<p><strong>为什么有偏向锁：</strong>因为经过HotSpot的作者大量的研究发现，大多数时候是不存在锁竞争的，常常是一个线程多次获得同一个锁，因此如果每次都要竞争锁会增大很多没有必要付出的代价，为了降低获取锁的代价，才引入的偏向锁</p>
<p><strong>偏向锁原理：</strong>当线程1访问代码块并获取锁对象时，会在java对象头和栈帧中记录偏向的锁的threadID，因为偏向锁不会主动释放锁，因此以后线程1再次获取锁的时候，需要比较当前线程的threadID和Java对象头中的threadID是否一致，如果一致（还是线程1获取锁对象），则无需使用CAS来加锁、解锁；如果不一致（其他线程，如线程2要竞争锁对象，而偏向锁不会主动释放因此还是存储的线程1的threadID），那么需要查看Java对象头中记录的线程1是否存活，如果没有存活，那么锁对象被重置为无锁状态，其它线程（线程2）可以竞争将其设置为偏向锁；如果存活，那么立刻查找该线程（线程1）的栈帧信息，如果还是需要继续持有这个锁对象，那么暂停当前线程1，撤销偏向锁，升级为轻量级锁，如果线程1 不再使用该锁对象，那么将锁对象状态设为无锁状态，重新偏向新的线程。</p>
<ul>
<li><h4 id="轻量锁"><a href="#轻量锁" class="headerlink" title="轻量锁"></a>轻量锁</h4></li>
</ul>
<p><strong>为什么有轻量级锁：</strong>轻量级锁考虑的是竞争锁对象的线程不多，而且线程持有锁的时间也不长的情景。因为阻塞线程需要CPU从用户态转到内核态，代价较大，如果刚刚阻塞不久这个锁就被释放了，那这个代价就有点得不偿失了，因此这个时候就干脆不阻塞这个线程，让它自旋这等待锁释放。</p>
<p><strong>轻量锁原理及升级过程：</strong>线程1获取轻量级锁时会先把锁对象的对象头MarkWord复制一份到线程1的栈帧中创建的用于存储锁记录的空间（称为DisplacedMarkWord），然后使用CAS把对象头中的内容替换为线程1存储的锁记录（DisplacedMarkWord）的地址；</p>
<p>如果在线程1复制对象头的同时（在线程1CAS之前），线程2也准备获取锁，复制了对象头到线程2的锁记录空间中，但是在线程2CAS的时候，发现线程1已经把对象头换了，线程2的CAS失败，那么线程2就尝试使用自旋锁来等待线程1释放锁。 自旋锁简单来说就是让线程2在循环中不断CAS（默认10次升级为重量锁）</p>
<ul>
<li><h4 id="重量锁"><a href="#重量锁" class="headerlink" title="重量锁"></a>重量锁</h4></li>
</ul>
<p><strong>为什么有轻量级锁</strong>：但是如果自旋的时间太长也不行，因为自旋是要消耗CPU的，因此自旋的次数是有限制的，比如10次或者100次，如果自旋次数到了线程1还没有释放锁，或者线程1还在执行，线程2还在自旋等待，这时又有一个线程3过来竞争这个锁对象，那么这个时候轻量级锁就会膨胀为重量级锁。重量级锁把除了拥有锁的线程都阻塞，防止CPU空转</p>
<p><img src="https://blog-cl.oss-cn-shenzhen.aliyuncs.com/%E9%94%81%E4%BC%98%E5%8A%A3%E5%8A%BF.png"></p>
<h2 id="5、synchronize和Lock锁的区别"><a href="#5、synchronize和Lock锁的区别" class="headerlink" title="5、synchronize和Lock锁的区别"></a>5、synchronize和Lock锁的区别</h2><p>1、synchronize是jvm层面关键字，Lock是一个接口，jdk提供了许多api</p>
<p>2、synchronize自动加锁释放锁，Lock需要手动</p>
<p>3、synchronize不可中断，lock可中断</p>
<p>4、synchronize是非公平锁，lock可以配置实现公平还是非公平锁</p>
<p>5、lock更加灵活，有丰富的api使用</p>
<h2 id="6、tips"><a href="#6、tips" class="headerlink" title="6、tips"></a>6、tips</h2><ul>
<li>错误的加锁方式</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 每次调用创建的是不同的锁，相当于无锁</span></span><br><span class="line"><span class="keyword">synchronized</span> (<span class="keyword">new</span> Object())</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> Integer count;</span><br><span class="line"><span class="comment">// String，Boolean在实现了都用了享元模式，即值在一定范围内，对象是同一个。所以看似是用了不同的对象，其实用的是同一个对象。会导致一个锁被多个地方使用</span></span><br><span class="line"><span class="keyword">synchronized</span> (count)</span><br></pre></td></tr></table></figure>



<ul>
<li>synchronized锁升级优化性能提升的体现</li>
</ul>
<p>ConcurrentHashMap在jdk1.7的时候，实现用的是分段锁，用ReentrantLock来保证并发安全。<br>而在jdk1.8的时候，抛弃了原有的分段锁，而采用了 CAS + synchronized 来保证并发安全性，也可以说明synchronized的的效率现在确实很高了。</p>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/" rel="tag">并发编程</a></li></ul>

    </footer>
  </div>

   
    
</article>

    
    <article
  id="post-volatile"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h2 itemprop="name">
  <a class="article-title" href="/2021/06/21/volatile/"
    >volatile</a> 
</h2>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2021/06/21/volatile/" class="article-date">
  <time datetime="2021-06-21T15:15:56.000Z" itemprop="datePublished">2021-06-21</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/">并发编程</a>
  </div>
   
    </div>
      
    <div class="article-entry" itemprop="articleBody">
       
  <h2 id="1、多线程情况下出现的问题"><a href="#1、多线程情况下出现的问题" class="headerlink" title="1、多线程情况下出现的问题"></a>1、多线程情况下出现的问题</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">VolatileTest</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> Integer  num = <span class="number">0</span>;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line"></span><br><span class="line">        Handler handler = <span class="keyword">new</span> Handler();</span><br><span class="line">        handler.start();</span><br><span class="line">        <span class="keyword">for</span> (;;)&#123;</span><br><span class="line">            <span class="keyword">if</span>(num &gt;<span class="number">0</span>)&#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;111&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Handler</span> <span class="keyword">extends</span> <span class="title">Thread</span></span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@SneakyThrows</span></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            Thread.sleep(<span class="number">500</span>);</span><br><span class="line">            num ++;</span><br><span class="line">            System.out.println(<span class="string">&quot;change:&quot;</span>+num);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面的代码永远都不可能打印“111”</p>
<h2 id="2、现代计算机内存模型"><a href="#2、现代计算机内存模型" class="headerlink" title="2、现代计算机内存模型"></a>2、现代计算机内存模型</h2><p>现代的计算机由于cpu效率要比内存快很多，为了避免cpu频繁等待内存读写，不得不设计出一块<strong>高速缓存（Cache）</strong>作为内存和cpu之间的缓冲。cpu在读取实例变量或者类变量的时候会首先去读高速缓存中的数据，如果没有再去内存中找，将内存中的数据拷贝一份到高速缓存中来，操作完之后会<strong>不定时</strong>的将高速缓存中的值刷新到变量副本中。</p>
<h2 id="3、java内存模型"><a href="#3、java内存模型" class="headerlink" title="3、java内存模型"></a>3、java内存模型</h2><p>java内存模型（jmm），是多线程情况下访问数据的一套规范，不与硬件产生一对一的对应关系。每个线程都对应一块单独的工作内存，在使用共享变量的时候需要从主存拷贝一个变量副本到工作空间，线程只能在自己的工作内存中完成所有操作（读，写），一个线程不能之间访问另一个线程的工作空间。</p>
<p>正是在这样的模型下会出现一些问题：</p>
<p>场景：线程1和线程2都需要读取主存中的一个共享变量（num = 0）</p>
<p>问题1：线程1读取并修改了变量num的值等于1，但是没刷新到主存，线程2这时候来主存获取num值仍然是0</p>
<p>问题2：线程1读取并修改了变量num的值等于1，并且刷新到了主存，但是线程2在线程1刷新到主存之前就获取num=0，此时线程2不知道值已被改变</p>
<p>上述的问题就是多线程场景下可能出现的可见性问题</p>
<h2 id="4、volatile解决的问题"><a href="#4、volatile解决的问题" class="headerlink" title="4、volatile解决的问题"></a>4、volatile解决的问题</h2><p><strong>使用volatile关键字修饰共享变量，解决可见性问题</strong></p>
<p>1、被volatile修饰的共享变量在工作线程中被修改过后会被立刻强制刷新到主存中去（解决上述出现的问题1）</p>
<p>2、强制刷新到主存中之后，还有可能会出现上述的问题2，如何保证各个线程的工作空间的缓存缓存一致性问题。MSEI(缓存一致性协议)，为了保证缓存一致性，cpu每个处理器之间制定的一个协议，当cpu在写一个变量是，如果是共享变量且存在其他变量副本，则会通知其他变量副本失效。</p>
<p>3、嗅探机制：每个处理器在总线上检查自己缓存的值是否过期，内存地址是否被更改，如果有更改则将缓存的值失效，下次需要使用的时候直接去主存读取（2-3解决上述问题2）</p>
<p><strong>使用volatile关键字修饰共享变量，防止指令重排序</strong></p>
<p>比如我们在使用双重检测锁的方式实现单例模式的时候</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SingleTest</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">volatile</span> <span class="keyword">static</span> SingleInstance singleInstance = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="title">SingleTest</span><span class="params">()</span> </span>&#123;&#125;;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> SingleInstance <span class="title">getInstance</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (singleInstance != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> singleInstance;</span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (SingleTest.class)&#123;</span><br><span class="line">                <span class="keyword">if</span>(singleInstance != <span class="keyword">null</span>)&#123;</span><br><span class="line">                    <span class="keyword">return</span> singleInstance;</span><br><span class="line">                &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">                    singleInstance = <span class="keyword">new</span> SingleInstance();</span><br><span class="line">                    <span class="keyword">return</span> singleInstance;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果不使用volatile关键字修饰单例变量，那么就有可能在new Singlestance()方法处出现问题。</p>
<p>正常的实例化对象的流程：</p>
<p>1、给实例开辟内存空间</p>
<p>2、实例初始化赋值</p>
<p>3、变量指向内存地址</p>
<p>由于JIT即时编译器的优化，在基于<code>as-if-serial</code>（不管如何重排序，单线程下的执行结果不能改变）的原则下，实例化对象的流程可能变成这样：</p>
<p>1、给实例开辟内存空间</p>
<p>2、变量指向内存地址</p>
<p>3、实例初始化赋值</p>
<p>此时如果刚好第2步执行完，时间片切换，下一个线程发现对象不为空。直接返回一个空的对象出去，此时就会发生空指针异常</p>
<p><strong>volatile使用内存屏障来阻止指令重拍</strong></p>
<p>volatile修饰的共享变量在读写的前后会加上内存屏障，屏障中的操作被禁止指令重拍</p>
<h2 id="5、知识点"><a href="#5、知识点" class="headerlink" title="5、知识点"></a>5、知识点</h2><p>1、volatile修饰的变量被修改会立刻强制刷回主存</p>
<p>2、处理器会通过嗅探机制判断自己的缓存是否失效</p>
<p>3、volatile不能保证原子性</p>
<p>4、volatile解决了可见性问题，和单例模式下的指令重排问题</p>
<p><strong>ps: 写测试代码过程中出现的问题</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">VolatileTest</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> Integer num = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line"></span><br><span class="line">        Handler handler = <span class="keyword">new</span> Handler();</span><br><span class="line">        handler.start();</span><br><span class="line">        <span class="keyword">for</span> (; ; ) &#123;</span><br><span class="line">        	<span class="comment">// 使用println输出共享变量，共享变量不加volatile关键字也没有可见性问题</span></span><br><span class="line">            System.out.println(num);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Handler</span> <span class="keyword">extends</span> <span class="title">Thread</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@SneakyThrows</span></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            Thread.sleep(<span class="number">500</span>);</span><br><span class="line">            num++;</span><br><span class="line">            System.out.println(<span class="string">&quot;change:&quot;</span> + num);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">println</span><span class="params">(String x)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">synchronized</span> (<span class="keyword">this</span>) &#123;</span><br><span class="line">            print(x);</span><br><span class="line">            newLine();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>最后先<code>println</code>方法中使用了<code>synchronize</code>关键字，所以在获取同步锁之后会清空工作空间中的缓存，再将要使用的变量从主存中拷贝到工作内存，所以此时打印的变量值是最新的值</p>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/" rel="tag">并发编程</a></li></ul>

    </footer>
  </div>

   
    
</article>

    
    <article
  id="post-JUC常用工具类"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h2 itemprop="name">
  <a class="article-title" href="/2021/06/20/JUC%E5%B8%B8%E7%94%A8%E5%B7%A5%E5%85%B7%E7%B1%BB/"
    >JUC常用工具类</a> 
</h2>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2021/06/20/JUC%E5%B8%B8%E7%94%A8%E5%B7%A5%E5%85%B7%E7%B1%BB/" class="article-date">
  <time datetime="2021-06-20T14:14:41.000Z" itemprop="datePublished">2021-06-20</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/">并发编程</a>
  </div>
   
    </div>
      
    <div class="article-entry" itemprop="articleBody">
       
  <h2 id="1、-CountDownLatch"><a href="#1、-CountDownLatch" class="headerlink" title="1、 CountDownLatch"></a>1、 CountDownLatch</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * A synchronization aid that allows one or more threads to wait until</span></span><br><span class="line"><span class="comment"> * a set of operations being performed in other threads completes.</span></span><br><span class="line"><span class="comment"> */</span> </span><br></pre></td></tr></table></figure>

<blockquote>
<p>countDownLatch类第一行注释，大意为该同步辅助工具可以允许一个或者多个线程等待同步辅助工具中的一组线程执行操作完成</p>
<p>场景：我约超哥，东哥，平仔吃饭</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CountDownLatchTest</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">        CountDownLatch countDownLatch = <span class="keyword">new</span> CountDownLatch(<span class="number">3</span>);</span><br><span class="line">        Thread thread1 = <span class="keyword">new</span> Thread(<span class="keyword">new</span> People(countDownLatch, <span class="string">&quot;东哥&quot;</span>));</span><br><span class="line">        Thread thread2 = <span class="keyword">new</span> Thread(<span class="keyword">new</span> People(countDownLatch, <span class="string">&quot;超哥&quot;</span>));</span><br><span class="line">        Thread thread3 = <span class="keyword">new</span> Thread(<span class="keyword">new</span> People(countDownLatch, <span class="string">&quot;平仔&quot;</span>));</span><br><span class="line"></span><br><span class="line">        thread1.start();</span><br><span class="line">        thread2.start();</span><br><span class="line">        thread3.start();</span><br><span class="line"></span><br><span class="line">        countDownLatch.await();</span><br><span class="line">        System.out.println(<span class="string">&quot;我终于吃上了饭&quot;</span>);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">People</span> <span class="keyword">implements</span> <span class="title">Runnable</span></span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">private</span> CountDownLatch countDownLatch;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">private</span> String name;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">People</span><span class="params">(CountDownLatch countDownLatch, String name)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">this</span>.countDownLatch = countDownLatch;</span><br><span class="line">            <span class="keyword">this</span>.name = name;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@SneakyThrows</span></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            doingSomething(RandomUtil.randomLong(<span class="number">1000</span>,<span class="number">5000</span>));</span><br><span class="line">            countDownLatch.countDown();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">doingSomething</span><span class="params">(Long time)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">            System.out.println(name + <span class="string">&quot;开始捯饬&quot;</span>);</span><br><span class="line">            Thread.sleep(time);</span><br><span class="line">            System.out.println(name + <span class="string">&quot;提裤子出门&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src="https://blog-cl.oss-cn-shenzhen.aliyuncs.com/JUC%E5%B7%A5%E5%85%B71.png"></p>
<blockquote>
<p>countDownLatch.await()方法执行，阻塞当前线程，直到countDownLatch.countDown()方法将count数量变为1时，线程才会接着运行</p>
<p>适用场景：多个线程拆分处理一个耗时任务，等所有线程处理完各自的任务之后，返回结果</p>
</blockquote>
<h2 id="2、CyclicBarrier"><a href="#2、CyclicBarrier" class="headerlink" title="2、CyclicBarrier"></a>2、CyclicBarrier</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * A synchronization aid that allows a set of threads to all wait for</span></span><br><span class="line"><span class="comment"> * each other to reach a common barrier point.  CyclicBarriers are</span></span><br><span class="line"><span class="comment"> * useful in programs involving a fixed sized party of threads that</span></span><br><span class="line"><span class="comment"> * must occasionally wait for each other. The barrier is called</span></span><br><span class="line"><span class="comment"> * &lt;em&gt;cyclic&lt;/em&gt; because it can be re-used after the waiting threads</span></span><br><span class="line"><span class="comment"> * are released.</span></span><br><span class="line"><span class="comment"> *</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>循环屏障：CyclicBarrier类第一行注释，大概意思为<strong>屏障</strong>：允许一组固定大小的线程等待所有线程共同达到屏障点之后才开始继续执行，<strong>循环</strong>:线程释放屏障之后，屏障可以重新使用</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CyclicBarrierTest</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 构造参数1：屏障点限制线程数</span></span><br><span class="line">        <span class="comment">// 构造参数2：所有线程达到屏障点之后执行，执行完之后屏障点前的线程开始走后续流程</span></span><br><span class="line">        CyclicBarrier cyclicBarrier = <span class="keyword">new</span> CyclicBarrier(<span class="number">2</span>, () -&gt; &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;各就位&quot;</span>);</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                Thread.sleep(<span class="number">2000</span>);</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">            System.out.println(<span class="string">&quot;跑&quot;</span>);</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 固定每次只有2个线程执行</span></span><br><span class="line">        ThreadPoolExecutor threadPoolExecutor = <span class="keyword">new</span> ThreadPoolExecutor(<span class="number">2</span>, <span class="number">2</span>,</span><br><span class="line">                <span class="number">0L</span>, TimeUnit.MILLISECONDS,</span><br><span class="line">                <span class="keyword">new</span> LinkedBlockingQueue&lt;Runnable&gt;());</span><br><span class="line">        threadPoolExecutor.execute(<span class="keyword">new</span> Ready(<span class="string">&quot;陈林&quot;</span>, cyclicBarrier));</span><br><span class="line">        threadPoolExecutor.execute(<span class="keyword">new</span> Ready(<span class="string">&quot;超哥&quot;</span>, cyclicBarrier));</span><br><span class="line">        threadPoolExecutor.execute(<span class="keyword">new</span> Ready(<span class="string">&quot;东哥&quot;</span>, cyclicBarrier));</span><br><span class="line">        threadPoolExecutor.execute(<span class="keyword">new</span> Ready(<span class="string">&quot;平仔&quot;</span>, cyclicBarrier));</span><br><span class="line"></span><br><span class="line">        threadPoolExecutor.shutdown();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Ready</span> <span class="keyword">implements</span> <span class="title">Runnable</span></span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">final</span> String name;</span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">final</span> CyclicBarrier cyclicBarrier;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">Ready</span><span class="params">(String name, CyclicBarrier cyclicBarrier)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">this</span>.name = name;</span><br><span class="line">            <span class="keyword">this</span>.cyclicBarrier = cyclicBarrier;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@SneakyThrows</span></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            System.out.println(name + <span class="string">&quot; 开始准备 &quot;</span>);</span><br><span class="line">            Thread.sleep(RandomUtil.randomLong(<span class="number">1000</span>,<span class="number">2000</span>));</span><br><span class="line">            System.out.println(name + <span class="string">&quot;准备完毕&quot;</span>);</span><br><span class="line">            <span class="comment">// 开始等待所有线程到达屏障点</span></span><br><span class="line">            cyclicBarrier.await();</span><br><span class="line">            System.out.println(name + <span class="string">&quot;开跑&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src="https://blog-cl.oss-cn-shenzhen.aliyuncs.com/JUC%E5%B7%A5%E5%85%B72.png"></p>
<blockquote>
<p>cyclicBarrier.await()方法，count-1，当count=0时达到临界点，所有等待线程开始执行，重新释放屏障，count重置为2</p>
</blockquote>
<h2 id="3、Semaphore"><a href="#3、Semaphore" class="headerlink" title="3、Semaphore"></a>3、Semaphore</h2><blockquote>
<p>计数信号量，可以维护一组许可，当这组许可被获取完之后，后面的线程需等待前面的线程释放线程</p>
<p>场景：我的100个同事排队核酸，因为义务人员有限，所以每次只能进去五个人做核酸，其余人需要等里面的人做完核酸再进去</p>
</blockquote>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line">public class SemaphoreTest &#123;</span><br><span class="line"></span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">    	// 定义一组5个许可</span><br><span class="line">        Semaphore semaphore = new Semaphore(5);</span><br><span class="line">        // 100个同事排队</span><br><span class="line">        for (int i = 0; i &lt; 100; i++) &#123;</span><br><span class="line">            new Thread(new NucleicAcidTest(semaphore,&quot;同事&quot;+i)).start();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    static class NucleicAcidTest implements Runnable&#123;</span><br><span class="line"></span><br><span class="line">        private Semaphore semaphore;</span><br><span class="line">        private String name;</span><br><span class="line"></span><br><span class="line">        public NucleicAcidTest(Semaphore semaphore, String name) &#123;</span><br><span class="line">            this.semaphore = semaphore;</span><br><span class="line">            this.name = name;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        @SneakyThrows</span><br><span class="line">        @Override</span><br><span class="line">        public void run() &#123;</span><br><span class="line">        	// 线程获取许可，获取到许可可以执行后续代码，许可为0的时候虚入队等待</span><br><span class="line">            semaphore.acquire();</span><br><span class="line">            System.out.println(name + &quot;开始核酸&quot;);</span><br><span class="line">            Thread.sleep(2000);</span><br><span class="line">            // 线程释放许可，唤醒队列中的线程</span><br><span class="line">            semaphore.release();</span><br><span class="line">            System.out.println(name + &quot;核酸结束&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>使用场景：流量控制</p>
</blockquote>
<h2 id="4、知识点"><a href="#4、知识点" class="headerlink" title="4、知识点"></a>4、知识点</h2><ul>
<li>CountDownLatch:  类中维护了一个Sync类继承AQS，是共享锁的一种实现，不可重复使用。</li>
<li>CyclicBarrier：类中维护了一个ReentrantLock非公平锁，可以在一组线程达到临界点时（count=0）执行自定义方法，放开这组线程执行，重置count数。可重复使用</li>
<li>Semaphore：类中维护了一个Sync类继承AQS，是共享锁的一种实现。分配一组许可，只允许同一时间内固定数量线程运行，其他线程队列等待。可配置公平锁还是非公平锁</li>
</ul>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/" rel="tag">并发编程</a></li></ul>

    </footer>
  </div>

   
    
</article>

    
    <article
  id="post-浅读AQS原理（一）"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h2 itemprop="name">
  <a class="article-title" href="/2021/06/19/%E6%B5%85%E8%AF%BBAQS%E5%8E%9F%E7%90%86%EF%BC%88%E4%B8%80%EF%BC%89/"
    >浅读AQS原理（一）</a> 
</h2>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2021/06/19/%E6%B5%85%E8%AF%BBAQS%E5%8E%9F%E7%90%86%EF%BC%88%E4%B8%80%EF%BC%89/" class="article-date">
  <time datetime="2021-06-18T16:21:06.000Z" itemprop="datePublished">2021-06-19</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/">并发编程</a>
  </div>
   
    </div>
      
    <div class="article-entry" itemprop="articleBody">
       
  <h2 id="1、什么是AQS"><a href="#1、什么是AQS" class="headerlink" title="1、什么是AQS"></a>1、什么是AQS</h2><p>AQS全称<code>AbstractQueuedSynchronizer</code>,一个用于方便实现各种锁的基础框架。<code>ReentrantLock</code>、<code>ReentrantReadWriteLock</code>、<code>CountDownLatch</code>、<code>Semaphore</code>等都是基于<code>AQS</code>来实现的。</p>
<h2 id="2、AQS类核心属性"><a href="#2、AQS类核心属性" class="headerlink" title="2、AQS类核心属性"></a>2、AQS类核心属性</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// FIFO等待队列头部</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">transient</span> <span class="keyword">volatile</span> Node head;</span><br><span class="line"><span class="comment">// FIFO等待队列尾部</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">transient</span> <span class="keyword">volatile</span> Node tail;</span><br><span class="line"><span class="comment">// 同步状态 state=0资源未被占用 state&gt;0资源被占用</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">volatile</span> <span class="keyword">int</span> state;</span><br><span class="line"><span class="comment">// AQS父类属性，独占锁当前占有线程</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">transient</span> Thread exclusiveOwnerThread;</span><br></pre></td></tr></table></figure>



<h2 id="3、分析reentrantLock-NonfairSync源码"><a href="#3、分析reentrantLock-NonfairSync源码" class="headerlink" title="3、分析reentrantLock.NonfairSync源码"></a>3、分析reentrantLock.NonfairSync源码</h2><ul>
<li><p>非公平锁调用lock()方法加锁</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">final</span> <span class="keyword">void</span> <span class="title">lock</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      <span class="keyword">if</span> (compareAndSetState(<span class="number">0</span>, <span class="number">1</span>))</span><br><span class="line">          setExclusiveOwnerThread(Thread.currentThread());</span><br><span class="line">      <span class="keyword">else</span></span><br><span class="line">          acquire(<span class="number">1</span>);</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure></li>
<li><p>线程A进入方法，cas尝试加锁</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">final</span> <span class="keyword">boolean</span> <span class="title">compareAndSetState</span><span class="params">(<span class="keyword">int</span> expect, <span class="keyword">int</span> update)</span> </span>&#123;</span><br><span class="line">   <span class="comment">// 基于unsfae类native方法完场cas操作</span></span><br><span class="line">   <span class="keyword">return</span> unsafe.compareAndSwapInt(<span class="keyword">this</span>, stateOffset, expect, update);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li><p>线程A加锁成功，设置当前线程占有锁</p>
</li>
<li><p>线程B进入方法，cas尝试加锁，加锁失败，走else方法，尝试获取锁</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">acquire</span><span class="params">(<span class="keyword">int</span> arg)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (!tryAcquire(arg) &amp;&amp;</span><br><span class="line">            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))</span><br><span class="line">            selfInterrupt();</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></li>
<li><p>调用<code>tryAcquire(arg)</code>方法尝试获得锁（<code>tryAcquire</code>方法为AQS类提供的模板方法，不同的锁有不同的实现，以下代码为<code>NonFair</code>类中的实现）</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">final</span> <span class="keyword">boolean</span> <span class="title">tryAcquire</span><span class="params">(<span class="keyword">int</span> acquires)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> nonfairTryAcquire(acquires);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">final</span> <span class="keyword">boolean</span> <span class="title">nonfairTryAcquire</span><span class="params">(<span class="keyword">int</span> acquires)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">final</span> Thread current = Thread.currentThread();</span><br><span class="line">      <span class="comment">// 获取当前锁状态</span></span><br><span class="line">      <span class="keyword">int</span> c = getState();</span><br><span class="line">      <span class="comment">// state=0,尝试加锁</span></span><br><span class="line">      <span class="keyword">if</span> (c == <span class="number">0</span>) &#123;</span><br><span class="line">          <span class="keyword">if</span> (compareAndSetState(<span class="number">0</span>, acquires)) &#123;</span><br><span class="line">              <span class="comment">// 加锁成功，设置独占锁占有线程</span></span><br><span class="line">              setExclusiveOwnerThread(current);</span><br><span class="line">              <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">          &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">// state&gt;0,判断占有线程是不是当线程（可重入锁）</span></span><br><span class="line">      <span class="keyword">else</span> <span class="keyword">if</span> (current == getExclusiveOwnerThread()) &#123;</span><br><span class="line">          <span class="comment">// 重入+1</span></span><br><span class="line">          <span class="keyword">int</span> nextc = c + acquires;</span><br><span class="line">          <span class="keyword">if</span> (nextc &lt; <span class="number">0</span>) <span class="comment">// overflow</span></span><br><span class="line">              <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">&quot;Maximum lock count exceeded&quot;</span>);</span><br><span class="line">              setState(nextc);</span><br><span class="line">              <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">            &#125;</span><br><span class="line">          <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">      &#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure></li>
<li><p><code>tryAcquire(arg)</code>获取资源失败执行<code>addWaiter(Node.EXCLUSIVE)</code>，将当前线程放入由AQS维护的双向链表中</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> Node <span class="title">addWaiter</span><span class="params">(Node mode)</span> </span>&#123;</span><br><span class="line">    	<span class="comment">//创建node节点封装当前线程</span></span><br><span class="line">        Node node = <span class="keyword">new</span> Node(Thread.currentThread(), mode);</span><br><span class="line">        <span class="comment">//获取队列中的尾结点</span></span><br><span class="line">        Node pred = tail;</span><br><span class="line">        <span class="keyword">if</span> (pred != <span class="keyword">null</span>) &#123;</span><br><span class="line">            node.prev = pred;</span><br><span class="line">            <span class="comment">//cas尝试将尾结点替换为当前节点</span></span><br><span class="line">            <span class="keyword">if</span> (compareAndSetTail(pred, node)) &#123;</span><br><span class="line">                pred.next = node;</span><br><span class="line">                <span class="keyword">return</span> node;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">   		<span class="comment">//cas替换尾结点失败</span></span><br><span class="line">    	<span class="comment">//enq方法自旋替换尾结点</span></span><br><span class="line">        enq(node);</span><br><span class="line">        <span class="keyword">return</span> node;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> Node <span class="title">enq</span><span class="params">(<span class="keyword">final</span> Node node)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">for</span> (;;) &#123;</span><br><span class="line">            Node t = tail;</span><br><span class="line">            <span class="keyword">if</span> (t == <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="keyword">if</span> (compareAndSetHead(<span class="keyword">new</span> Node()))</span><br><span class="line">                    tail = head;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                node.prev = t;</span><br><span class="line">                <span class="keyword">if</span> (compareAndSetTail(t, node)) &#123;</span><br><span class="line">                    t.next = node;</span><br><span class="line">                    <span class="keyword">return</span> t;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></li>
<li><p>将线程节点放入队列之后，获取队列中的线程节点，执行<code>acquireQueued</code>方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">acquire</span><span class="params">(<span class="keyword">int</span> arg)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (!tryAcquire(arg) &amp;&amp;</span><br><span class="line">            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))</span><br><span class="line">            selfInterrupt();</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line"><span class="function"><span class="keyword">final</span> <span class="keyword">boolean</span> <span class="title">acquireQueued</span><span class="params">(<span class="keyword">final</span> Node node, <span class="keyword">int</span> arg)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">boolean</span> failed = <span class="keyword">true</span>;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">boolean</span> interrupted = <span class="keyword">false</span>;</span><br><span class="line">            <span class="keyword">for</span> (;;) &#123;</span><br><span class="line">            	<span class="comment">// 获取当前节点上一个节点</span></span><br><span class="line">                <span class="keyword">final</span> Node p = node.predecessor();</span><br><span class="line">                <span class="comment">// 如果当前节点上一个节点为头结点（头结点为当前占有资源的节点）</span></span><br><span class="line">                <span class="comment">// 尝试获取资源，加锁</span></span><br><span class="line">                <span class="keyword">if</span> (p == head &amp;&amp; tryAcquire(arg)) &#123;</span><br><span class="line">                	<span class="comment">// 加锁成功</span></span><br><span class="line">                	<span class="comment">// 将头结点设置为当前节点</span></span><br><span class="line">                    setHead(node);</span><br><span class="line">                    p.next = <span class="keyword">null</span>; <span class="comment">// help GC</span></span><br><span class="line">                    failed = <span class="keyword">false</span>;</span><br><span class="line">                    <span class="keyword">return</span> interrupted;</span><br><span class="line">                &#125;</span><br><span class="line">                </span><br><span class="line">                <span class="comment">// 当前节点的上一个节点非头结点或者头结点未释放资源，加锁失败</span></span><br><span class="line">                <span class="comment">// 判断当前节点状态，是否需要中断线程</span></span><br><span class="line">                <span class="comment">// 如果不中断，则自旋获取资源</span></span><br><span class="line">                <span class="keyword">if</span> (shouldParkAfterFailedAcquire(p, node) &amp;&amp;</span><br><span class="line">                    parkAndCheckInterrupt())</span><br><span class="line">                    interrupted = <span class="keyword">true</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (failed)</span><br><span class="line">                cancelAcquire(node);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></li>
<li><p>加锁失败</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">acquire</span><span class="params">(<span class="keyword">int</span> arg)</span> </span>&#123;</span><br><span class="line">		<span class="comment">// 获取资源失败 &amp;&amp; 当前线程节点需要终端</span></span><br><span class="line">        <span class="keyword">if</span> (!tryAcquire(arg) &amp;&amp;</span><br><span class="line">            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))</span><br><span class="line">            <span class="comment">// 终端当前线程</span></span><br><span class="line">            selfInterrupt();</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></li>
</ul>
<h2 id="4、reentrantLock公平锁大概执行流程"><a href="#4、reentrantLock公平锁大概执行流程" class="headerlink" title="4、reentrantLock公平锁大概执行流程"></a>4、reentrantLock公平锁大概执行流程</h2><p><img src="https://blog-cl.oss-cn-shenzhen.aliyuncs.com/aqs-reentrantLock.png"></p>
<ul>
<li><p><code>reentrantLock</code>公平锁的执行流程与非公平锁执行流程基本相似，只是在获取资源之前会先判断等待队列中有没有线程在排队，如果有不尝试加锁，直接加入队列尾部排队</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">final</span> <span class="keyword">boolean</span> <span class="title">tryAcquire</span><span class="params">(<span class="keyword">int</span> acquires)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">final</span> Thread current = Thread.currentThread();</span><br><span class="line">            <span class="keyword">int</span> c = getState();</span><br><span class="line">            <span class="keyword">if</span> (c == <span class="number">0</span>) &#123;</span><br><span class="line">            	<span class="comment">// hasQueuedPredecessors方法返回false,没有线程在排队，再尝试加锁</span></span><br><span class="line">                <span class="keyword">if</span> (!hasQueuedPredecessors() &amp;&amp;</span><br><span class="line">                    compareAndSetState(<span class="number">0</span>, acquires)) &#123;</span><br><span class="line">                    setExclusiveOwnerThread(current);</span><br><span class="line">                    <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span> <span class="keyword">if</span> (current == getExclusiveOwnerThread()) &#123;</span><br><span class="line">                <span class="keyword">int</span> nextc = c + acquires;</span><br><span class="line">                <span class="keyword">if</span> (nextc &lt; <span class="number">0</span>)</span><br><span class="line">                    <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">&quot;Maximum lock count exceeded&quot;</span>);</span><br><span class="line">                setState(nextc);</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">        &#125;</span><br></pre></td></tr></table></figure></li>
</ul>
<h2 id="5、知识点"><a href="#5、知识点" class="headerlink" title="5、知识点"></a>5、知识点</h2><ul>
<li>模板模式</li>
<li>公平锁，非公平锁</li>
<li>可重入锁</li>
</ul>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/" rel="tag">并发编程</a></li></ul>

    </footer>
  </div>

   
    
</article>

    
  </article>
  

  
</section>
</div>

      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2021
        <i class="ri-heart-fill heart_icon"></i> Bian Dou
      </li>
    </ul>
    <ul>
      <li>
        
        
        
        Powered by <a href="https://hexo.io" target="_blank">Hexo</a>
        <span class="division">|</span>
        Theme - <a href="https://github.com/Shen-Yu/hexo-theme-ayer" target="_blank">Ayer</a>
        
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
      </li>
    </ul>
  </div>
</footer>
      <div class="float_btns">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

      </div>
    </main>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="豆 扁"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/alipay.jpg">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/wechat.jpg">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>
 
<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css"
/>
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->
 <!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script> 
<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->

<!-- ClickLove -->
 
<script src="/js/clickLove.js"></script>
 
<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->
 
<link rel="stylesheet" href="/css/clipboard.css">
 <script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>
 
<!-- CanvasBackground -->

<script>
  if (window.mermaid) {
    mermaid.initialize({ theme: "forest" });
  }
</script>


    
  </div>
</body>

</html>